package com.capgemini.cn.authority.data.entity;

import com.capgemini.cn.authority.data.core.BaseEntity;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import java.util.List;

/**
 * <p>角色表</p>
 * Created at 2017/8/23
 *
 * @author Andriy
 */
@Entity
@Table(name = "cg_roles")
@NoArgsConstructor
@AllArgsConstructor
public class Roles extends BaseEntity {

    /**
     * 角色名称
     */
    @Column(name = "role_name", length = 50, nullable = false)
    @Getter
    @Setter
    private String roleName;

    /**
     * 角色与用户组的多对多关系，用以获得当前用户组所属的角色信息
     */
    @ManyToMany(targetEntity = Groups.class, mappedBy = "roles")
    @Getter
    @Setter
    private List<Groups> groupsList;

    /**
     * <p>角色与权限的多对多关系</p>
     * <p>关系维护者为{@link Roles}对象，即对应的角色被删除时相应关联的权限关系也会一并被解除，反之移除对应的权限数据之前需先手动解除角色与权限数据的关系</p>
     */
    @ManyToMany(targetEntity = Authorities.class, cascade = {
            CascadeType.DETACH
    })
    @JoinTable(name = "cg_role_authorities", joinColumns = {
            @JoinColumn(name = "role_id", referencedColumnName = "id", nullable = false, updatable = false)
    }, inverseJoinColumns = {
            @JoinColumn(name = "authority_id", referencedColumnName = "id", nullable = false, updatable = false)
    })
    @Getter
    @Setter
    private List<Authorities> authorities;

    public Roles(String roleName) {
        this.roleName = roleName;
    }
}
